/*  header-comment
/*  file   : index
/*  author : ztf
/*  date   : 2017-8-24
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { createForm } from "rc-form";
import { SearchBar, InputItem, List } from "@ali/ding-ui";
import Icon from "../../components/Icon"
import { bindActionCreators } from "redux";
import { connect } from "react-redux";

// utils
import { setLeft } from "../../utils/dingtalk.js";

// actions
import {
  getSchoolData,
  getSchoolInitData
} from "../../actions/steps/getFiles.js";

// less
import "./index.less";
//将store注入组件的props
const mapStateToProps = state => ({ source: state.STEPS_STEPONE });
//将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  //区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      getSchoolData,
      getSchoolInitData
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
class SchoolChooser extends Component {
  static defaultProps = {};
  //propTypes 验证
  static propTypes = {
    initialValue: PropTypes.string,
    value: PropTypes.string,
    onChange: PropTypes.func,
    readonly: PropTypes.bool,
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,

      getSchoolInitData: PropTypes.func.isRequired,
      getSchoolData: PropTypes.func.isRequired
    }).isRequired
  };
  constructor(props) {
    super(props);

    this.state = {
      schools: [],
      inputVal: "",
      showSchools: false,
      imgUrl: "",
      searchVal: ""
    };
    const backHandler = () => {
      this.setState({
        showSearchBar: false
      });
    };
    if (dd.android) {
      document.addEventListener("backbutton", backHandler, false);
    }
  }

  componentWillMount = () => {
    this.props.actions.getSchoolInitData(this.props.value, { showLoading: false })
      .then(res => {
        if (res.success) {
          const { result } = res;
          const { schoolName, schoolMobileUrl } = result;

          this.setState({
            inputVal: schoolName,
            imgUrl: schoolMobileUrl,
            searchVal: schoolName
          });
        }
      });
  };

  componentWillReceiveProps(nextProps) {
    if (!nextProps.value) return;
    const { initialValue, value } = nextProps;
    const { value: currentSchoolName } = this.props;
    const schoolName = value || initialValue;

    if (schoolName !== currentSchoolName) {
      this.props.actions.getSchoolInitData(schoolName).then(res => {
        if (res.success) {
          const { result } = res;
          const { schoolName, schoolMobileUrl } = result;

          this.setState({
            inputVal: schoolName,
            imgUrl: schoolMobileUrl,
            searchVal: schoolName
          });
        }
      });
    }
  }

  onChange = searchVal => {
    this.setState({
      searchVal
    });
    if (escape(searchVal).indexOf("%u") >= 0) {
      this.props.actions.getSchoolData(searchVal).then(res => {
        if (res.success) {
          const { result } = res;
          this.setState({
            schools: result,
            showSchools: true
          });
        } else {
          this.setState({
            showSchools: false
          });
        }
      });
    }
    if (this.state.inputVal === "") {
      this.setState({
        showSchools: false
      });
    }
  };

  handleSelectOption = (imgUrl, value) => {
    this.setState({
      showSchools: false,
      imgUrl: imgUrl,
      inputVal: value,
      showSearchBar: false,
      searchVal: value
    });
    this.props.onChange && this.props.onChange(value);
    setLeft({});
  };

  handleClear = () => {
    this.setState({
      inputVal: "",
      imgUrl: ""
    });
    this.props.onChange("");
  };

  handleback = () => {
    this.setState({
      showSchools: false,
      showSearchBar: false
    });
    setLeft({});
  };

  handleScroll = () => {
    document
      .querySelector("#schoolChooser")
      .addEventListener("touchmove", function(e) {
        e.preventDefault();
      });
  };

  render() {
    const { schools, inputVal, showSchools, imgUrl, searchVal } = this.state;
    const readonly = this.props.readonly;

    const children = schools.map((item, index) => (
      <div
        onClick={() =>
          this.handleSelectOption(item.schoolMobileUrl, item.schoolName)}
        className="search-list"
        key={index}
      >
        <span className="search-list-logo">
          <img
            className="schoolLogo"
            src={item.schoolMobileUrl}
            alt={item.schoolName}
          />
        </span>
        <span>{item.schoolName}</span>
      </div>
    ));

    return (
      <div>
        {readonly ? (
          <div className="graduteSchool">
            <div className="preview-profile-group">
              <span className="school-title preview-profile-field">毕业院校</span>
              {imgUrl && (
                <span className="schoolImg ">
                  <img src={imgUrl} />
                </span>
              )}

              <span className="school-name preview-profile-field">
                {inputVal || "-"}
              </span>
            </div>
          </div>
        ) : (
          <List.Item>
            {this.props.children}
            <lable className="getSchool">
              毕业院校
              {imgUrl &&
              this.props.value && (
                <img
                  className="schoolLogo"
                  style={{ display: "inline-block" }}
                  src={imgUrl}
                />
              )}
              {this.props.value && (
                <div
                  className="school_clear_btn"
                  onClick={() => this.handleClear()}
                >
                  <Icon type="cross-circle-o" size="xs" color="#c8c8cd" />
                </div>
              )}
              <InputItem
                style={{ display: "inline-block" }}
                placeholder="请输入"
                onFocus={() => {
                  document.querySelector(".getSchool input").blur();
                  this.setState({ searchVal: inputVal });
                  if (dd.android) {
                    this.setState({ showSearchBar: true });
                    history.pushState(
                      "",
                      "",
                      `#steps?modal=${new Date().getTime()}`
                    );
                  } else {
                    this.setState({ showSearchBar: true }, () => {
                      this.handleScroll();
                      setLeft({
                        onClick: () =>
                          this.setState(
                            {
                              showSearchBar: false
                            },
                            setLeft({})
                          )
                      });
                    });
                  }
                }}
                value={this.props.value}
              />
            </lable>
            {this.state.showSearchBar && (
              <div className="alertSchool needsclick" id="schoolChooser">
                <div className="search needsclick">
                  <SearchBar
                    value={searchVal}
                    placeholder="学校（例如：清华大学）"
                    showCancelButton
                    autoFocus={true}
                    onCancel={this.handleback}
                    onChange={this.onChange}
                    className={"needsclick"}
                  />
                  {showSchools ? (
                    <div className="search-section">{children}</div>
                  ) : (
                    ""
                  )}
                </div>
              </div>
            )}
          </List.Item>
        )}
      </div>
    );
  }
}
export default createForm()(SchoolChooser);
